package com.example.plugin_get_version

import android.content.pm.PackageInfo
import androidx.annotation.NonNull
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result

/** 获取APP版本号 */
class PluginGetVersionPlugin : FlutterPlugin, MethodCallHandler {
    private lateinit var channel: MethodChannel
    private lateinit var packageInfo: PackageInfo
    override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "plugin_get_version")
        channel.setMethodCallHandler(this)
        packageInfo = flutterPluginBinding.applicationContext.packageManager.getPackageInfo(
            flutterPluginBinding.applicationContext.packageName,
            0
        )
    }

    override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
        return when (call.method) {
            "getPlatformVersion" -> result.success("Android ${android.os.Build.VERSION.RELEASE}")
            "getAppVersionCode" -> result.success(packageInfo.versionCode.toString())
            "getAppVersionName" -> result.success(packageInfo.versionName)
            else -> result.notImplemented()
        }
    }

    override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
    }
}
